using Admin2025.Application.Events;
using MediatR;
using Microsoft.Extensions.Logging;

namespace Admin2025.Application.EventHandlers;

/// <summary>
/// 用户删除事件处理器 - 清理相关数据
/// </summary>
public class UserDeletedCleanupHandler : INotificationHandler<UserDeletedNotification>
{
    private readonly ILogger<UserDeletedCleanupHandler> _logger;

    public UserDeletedCleanupHandler(ILogger<UserDeletedCleanupHandler> logger)
    {
        _logger = logger;
    }

    public async Task Handle(UserDeletedNotification notification, CancellationToken cancellationToken)
    {
        var userEvent = notification.UserDeletedEvent;
        
        _logger.LogInformation("开始清理用户相关数据: 事件ID={EventId}, 用户ID={UserId}, 用户名={Username}", 
            userEvent.EventId, userEvent.UserId, userEvent.Username);

        try
        {
            // 模拟清理用户相关数据
            await CleanupUserData(userEvent.UserId);
            
            _logger.LogInformation("用户数据清理完成: 用户ID={UserId}", userEvent.UserId);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "用户数据清理失败: 用户ID={UserId}", userEvent.UserId);
        }
    }

    private async Task CleanupUserData(Guid userId)
    {
        // 模拟清理操作：
        // 1. 清理用户缓存
        // 2. 删除用户文件
        // 3. 清理用户会话
        // 4. 通知相关系统
        
        await Task.Delay(50); // 模拟异步操作
        _logger.LogInformation("用户相关数据已清理: 用户ID={UserId}", userId);
    }
}
